package ufc.quixada.petti.service;

import java.util.List;

import ufc.quixada.petti.dao.ParticipanteDAO;
import ufc.quixada.petti.infra.SimplesEntityManager;
import ufc.quixada.petti.model.Participante;



public class ParticipanteService {
	private ParticipanteDAO dao;

	private SimplesEntityManager simpleEntityManager;

	public ParticipanteService() {

	}

	public ParticipanteService(SimplesEntityManager simpleEntityManager) {
		this.simpleEntityManager = simpleEntityManager;
		dao = new ParticipanteDAO(simpleEntityManager.getEntityManager());
	}

	public void save(Participante participante) {

		try {
			simpleEntityManager.beginTransaction();
			dao.save(participante);
			simpleEntityManager.commit();
		} catch (Exception e) {
			e.printStackTrace();
			simpleEntityManager.rollBack();
		} 

	}

	public List<Participante> findAll() {
		return dao.findAll();
	}

	public void atualizar(Participante participante) {

		try {
			simpleEntityManager.beginTransaction();
			dao.update(participante);
			simpleEntityManager.commit();
		} catch (Exception e) {
			e.printStackTrace();
			simpleEntityManager.rollBack();
		} finally {
			simpleEntityManager.close();
		}
	}

	public void remover(Participante participante) {
		try {
			simpleEntityManager.beginTransaction();
			dao.delete(participante);
			simpleEntityManager.commit();
		} catch (Exception e) {
			e.printStackTrace();
			simpleEntityManager.rollBack();
		} finally {
			simpleEntityManager.close();
		}
	}

	public Participante findById(Long id) {
		Participante participante = null;
		try {
			simpleEntityManager.beginTransaction();
			participante = dao.getById(id);
			simpleEntityManager.commit();
		} catch (Exception e) {
			e.printStackTrace();
			simpleEntityManager.rollBack();
		} finally {
			simpleEntityManager.close();
		}
		return participante;
	}

	public Participante removerPorId(Long id) {
		Participante participante = null;
		try {
			simpleEntityManager.beginTransaction();
			participante = dao.getById(id);
			dao.delete(participante);
			simpleEntityManager.commit();
		} catch (Exception e) {
			e.printStackTrace();
			simpleEntityManager.rollBack();
		} finally {
			simpleEntityManager.close();
		}
		return participante;
	}

	public Participante encontrarPorNome(String nome) {
		Participante participante = null;
		try {
			simpleEntityManager.beginTransaction();
			 participante = dao.getByName(nome);
			simpleEntityManager.commit();
		} catch (Exception e) {
			e.printStackTrace();
			simpleEntityManager.rollBack();
		} finally {
			simpleEntityManager.close();
		}
		return participante;
	}

}
